package com.neusoft.oa.controller.Email;


import com.neusoft.oa.pojo.Email;
import com.neusoft.oa.pojo.Percontact;
import com.neusoft.oa.service.IWriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/write")
@CrossOrigin
public class WriteController {

    @Autowired
    IWriteService writeService;

    @RequestMapping("contact")
    public List<com.neusoft.oa.pojo.Percontact> list(Percontact percontact){
        return writeService.writeList(percontact);
    }

    @RequestMapping("check")
    public List<com.neusoft.oa.pojo.Percontact> checklist(String checkname){
        return writeService.checkList(checkname);
    }

    @RequestMapping("insert")
    public boolean insert(Email email){
        return writeService.emailInsert(email);
    }

    @RequestMapping("upload")
    public String uploadFile(MultipartFile file, HttpServletRequest req) throws IOException {
        if(!file.isEmpty()){
            //获得服务器地址
            String uploadPath = req.getServletContext().getRealPath("/upfiles/");
            System.out.println("上传地址："+uploadPath);

            File uploadDir = new File(uploadPath);
            if(!uploadDir.exists()){
                uploadDir.mkdir();//如果目录不存在则创建
            }
            String OriginalFilename = file.getOriginalFilename();
            String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));
            //重新随机生成名字
            String filename = UUID.randomUUID().toString() +suffixName;
            File serverFile = new File(uploadPath+"\\"+filename);
            try {
                file.transferTo(serverFile);
                System.out.println(filename+">>>>>>>>");
                return "http://localhost:8080/upfiles/"+filename;
            }catch (IOException e){
                e.printStackTrace();
                System.out.println("上传失败");
                return "";
            }
        }else {
            System.out.println("文件为空");
            return "";
        }
    }

}
